// pages/order/create.js
const App = getApp()
const CryptoJS = require('crypto-js')
import Kits from '../../utils/kits'
import Util from '../../utils/util'

Page({
  data: {
    init: false,
    showModal: false,

    car: {},
    user: {},
    timeok: 'check',
    begin: {
      value: undefined,
      year: '',
      date: '',
      time: '',
    },
    close: {
      value: undefined,
      year: '',
      date: '',
      time: '',
    },
    hdays: '',

    method: 1,

    self: true,
    pickerSelect: false,
    picker: {},
    pickers: [],
    pindex: undefined,

    depotype: 1,

    memo: '',

    dayp: 0,
    bamt: 0,

    svc_onsite: false,
    svc_remote: false,
    svc_bins: false,
    svc_dins: false,
    svc_tins: false,
    svc_free: false,

    onsite_area: '',
    onsite_addr: '',
    onsite_locs: '',

    invoice: {},

    prices: {},
    price: {},

    feeDetails: [],
    feeDetail: false
  },

  onLoad(options) {
    this.doSetDates(new Date(parseInt(options.begin)), new Date(parseInt(options.close)))
    this.setData({
      svc_onsite: options.onsite == 'true',
      onsite_area: options.onsite_area,
      onsite_locs: options.onsite_locs,
      onsite_addr: options.onsite_addr,
    })
    this.execLoad(options)
    wx.sub('ReloadUserInfo', this, () => {
      this.execLoadUser()
    })
    this.execLoadUser()
    wx.sub('ReloadPickerInfo', this, () => {
      this.execLoadPicker()
    })
    this.execLoadPicker()
  },
  onUnload() {
    wx.cancel('ReloadUserInfo', this)
    wx.cancel('ReloadPickerInfo', this)
  },
  execLoad(options) {
    App.doPost({
      uri: '/app/base/biz/car/detail',
      body: {
        id: options.carid,
      },
      fnSucc: resp => {

        resp.data.price.pdpStr = Kits.fmtMoneyString(resp.data.price.pdp)
        resp.data.price.pmpStr = Kits.fmtMoneyString(resp.data.price.pmp)
        resp.data.price.mdpStr = Kits.fmtMoneyString(resp.data.price.mdp)
        resp.data.price.depositStr = Kits.fmtMoneyString(resp.data.price.deposit)
        resp.data.price.dispStr = Kits.fmtMoneyString(resp.data.price.disp)


        resp.data.service.onsite.memo = `${Kits.fmtKilometreString(resp.data.service.onsite.meter)}公里内${Kits.fmtMoneyString(resp.data.service.onsite.cost)}元，超出后每公里${Kits.fmtMoneyString(resp.data.service.onsite.mile)}元`
        resp.data.service.remote.memo = `${Kits.fmtKilometreString(resp.data.service.remote.meter)}公里内${Kits.fmtMoneyString(resp.data.service.remote.cost)}元，超出后每公里${Kits.fmtMoneyString(resp.data.service.remote.mile)}元`
        resp.data.service.bins.memo = `每天${Kits.fmtMoneyString(resp.data.service.bins.cost)}元，封顶${Kits.fmtMoneyString(resp.data.service.bins.max)}元`
        resp.data.service.dins.memo = `每天${Kits.fmtMoneyString(resp.data.service.dins.cost)}元，封顶${Kits.fmtMoneyString(resp.data.service.dins.max)}元`
        resp.data.service.tins.memo = `${resp.data.service.tins.quota}万元三者保额，15天收取${Kits.fmtMoneyString(resp.data.service.tins.cost)}元`
        resp.data.service.free.memo = `${Kits.fmtMoneyString(resp.data.service.free.quota)}元以内，7天收取${Kits.fmtMoneyString(resp.data.service.free.cost)}元`
        resp.data.service.night.memo = `22点-次日7点，每次收费${Kits.fmtMoneyString(resp.data.service.night.cost)}元`
        this.setData({
          car: resp.data,
          init: true
        })
        this.execCheckTime()
        this.execCalcPrice()
      },
      fnFail: resp => {
        Util.Notify.error(`[${resp.stat.err}] ${resp.stat.msg}`)
      },
      fnComp: () => {
        this.setData({
          loading: false
        })
      }
    })
  },
  // 加载用户信息
  execLoadUser() {
    App.doPost({
      uri: '/app/user/info/profile/info',
      body: {},
      fnSucc: resp => {
        this.setData({
          user: resp.data
        })
      }
    })
  },
  // 关闭弹窗
  closeModal() {
      this.setData({
        showModal: false
      })
  },
  // 加载取车人
  execLoadPicker() {
    App.doPost({
      uri: '/app/user/picker/list',
      body: {},
      fnSucc: resp => {
        this.setData({

          pickers: resp.data.items
        })
      },
    })
  },
  // 检查租赁时间是否可用
  execCheckTime() {
    if (!this.data.car.id) {
      return
    }
    this.setData({
      timeok: 'check'
    })
    App.doPost({
      uri: '/app/base/biz/car/state',
      body: {
        id: this.data.car.id,
        begin: new Date(this.data.begin.value).format('yyyy-MM-dd HH:mm:ss'),
        close: new Date(this.data.close.value).format('yyyy-MM-dd HH:mm:ss')
      },
      fnSucc: resp => {
        this.setData({
          timeok: resp.data.flag ? 'true' : 'false'
        })
      }
    })
  },
  // 计算价格
  execCalcPrice() {
    if (!this.data.init) {
      return
    }
    this.setData({
      price: {}
    })
    if (this.data.method != 1 && this.data.dayp == 0) {
      return
    }
    if (this.data.method != 1) {
      let bamt = this.data.dayp - parseFloat(this.data.car.price.pdpStr)
      if (bamt <= 0) {
        return
      }
      this.setData({
        bamt: bamt
      })
    }
    if ((this.data.svc_onsite || this.data.svc_remote) && this.data.onsite_locs == '') {
      return
    }
    let body = {
      cid: this.data.car.id,
      mem: false,
      uid: App.Global.User.id,
      begin: new Date(this.data.begin.value).format('yyyy-MM-dd HH:mm:ss'),
      close: new Date(this.data.close.value).format('yyyy-MM-dd HH:mm:ss'),
      method: this.data.method,
      mine: {},
      entrust: {
        day: parseInt(parseFloat(this.data.dayp) * 100),
      },
      custom: {
        day: parseInt(parseFloat(this.data.dayp) * 100)
      },
      onsite: {
        flag: this.data.svc_onsite,
        area: this.data.onsite_area,
        addr: this.data.onsite_addr,
        locs: this.data.onsite_locs
      },
      remote: {
        flag: this.data.svc_remote,
        area: this.data.onsite_area,
        addr: this.data.onsite_addr,
        locs: this.data.onsite_locs
      },
      service: {
        bins: this.data.svc_bins,
        dins: this.data.svc_dins,
        tins: this.data.svc_tins,
        free: this.data.svc_free
      },
      deposit: this.data.depotype
    }

    let md5 = CryptoJS.MD5(JSON.stringify(body)).toString()
    if (this.data.prices[md5] != undefined) {
      this.setData({
        price: this.data.prices[md5],
        feeDetails: this.data.prices[md5].fees,
      })
      return
    }
    App.doPost({
      uri: '/app/base/order/create/price/calc',
      body: body,
      fnSucc: resp => {
        resp.data.totalStr = Kits.fmtMoneyString(resp.data.total)
        resp.data.brokerageStr = Kits.fmtMoneyString(resp.data.bamt)
        this.data.prices[md5] = resp.data
        this.setData({
          price: resp.data,
          feeDetails: resp.data.fees,
        })
      },
      fnFail: resp => {
        Util.Notify.error(`[${resp.stat.err}] ${resp.stat.msg}`)
      },
      fnComp: () => {
        this.setData({
          loading: false
        })
      }
    })
  },
  // 创建订单
  execCreate() {
    if (!this.data.init) {
      return
    }
    if (this.data.user.idc.state == 0 || this.data.self && this.data.user.dlc.state == 0) {
        this.setData({
            showModal: true
        })
        return
    }
    if (this.data.timeok != 'true') {
      Util.Toast.fail('该时间无法出租')
      return
    }
    if (this.data.method != 1 && this.data.dayp == 0) {
      Util.Toast.fail('请填写每日租金')
      return
    }
    if ((this.data.svc_onsite || this.data.svc_remote) && this.data.onsite_locs == '') {
      Util.Toast.fail('请选择送车位置')
      return
    }
    if (this.data.self) {
      if (this.data.user.idc.state == 0 || this.data.user.dlc.state == 0) {
        Util.Toast.fail('请在个人信息认证后下单')
        return
      }
    } else {
      if (this.data.user.idc.state == 0) {
        Util.Toast.fail('请在个人信息认证后下单')
        return
      }
      if (!this.data.picker.id) {
        Util.Toast.fail('请选择取车人')
        return
      }
    }

    let body = {
      id: this.data.car.id,
      begin: new Date(this.data.begin.value).format('yyyy-MM-dd HH:mm:ss'),
      close: new Date(this.data.close.value).format('yyyy-MM-dd HH:mm:ss'),
      method: this.data.method,
      clk:this.data.clk,
      mine: {
        dlc: this.data.self ? this.data.user.dlc.id : this.data.picker.id,
      },
      entrust: {
        day: parseInt(parseFloat(this.data.dayp) * 100),
      },
      custom: {
        day: parseInt(parseFloat(this.data.dayp) * 100)
      },
      onsite: {
        flag: this.data.svc_onsite,
        area: this.data.onsite_area,
        addr: this.data.onsite_addr,
        locs: this.data.onsite_locs
      },
      remote: {
        flag: this.data.svc_remote,
        area: this.data.onsite_area,
        addr: this.data.onsite_addr,
        locs: this.data.onsite_locs
      },
      service: {
        bins: this.data.svc_bins,
        dins: this.data.svc_dins,
        tins: this.data.svc_tins,
        free: this.data.svc_free
      },
      deposit: this.data.depotype,
      memo: this.data.memo,
      invoice: this.data.invoice,
    }
    const text = JSON.stringify(body,null,2)
    console.log(text,"text")
    App.doPost({
      uri: '/app/order/create/submit',
      body: body,
      fnSucc: resp => {
        let info = {
          id: resp.data.id,
          expire: resp.data.expire,
          total: resp.data.total
        }
        wx.redirectTo({
          url: `/pages/order/pay?src=create&biz=Rent&info=${ JSON.stringify(info) }`,
        })
      },
      fnFail: resp => {
        Util.Notify.error(`[${resp.stat.err}] ${resp.stat.msg}`)
      },
      fnComp: () => {
        this.setData({
          loading: false
        })
      }
    })
  },
  // 创建分享
  execShare() {
    if (!this.data.init) {
      return
    }
    if (this.data.timeok != 'true') {
      Util.Toast.fail('该时间无法出租')
      return
    }
    if (this.data.dayp == 0) {
      Util.Toast.fail('请填写每日租金')
      return
    }
    if (this.data.dayp <= parseFloat(this.data.car.price.pdpStr)) {
      Util.Toast.fail('租金不得低于调车价')
      return
    }
    if ((this.data.svc_onsite || this.data.svc_remote) && this.data.onsite_locs == '') {
      Util.Toast.fail('请选择送车位置')
      return
    }
    if (!this.data.price.totalStr) {
      return
    }
    let body = {
      id: this.data.car.id,
      clk: App.Global.User.id,
      begin: new Date(this.data.begin.value).format('yyyy-MM-dd HH:mm:ss'),
      close: new Date(this.data.close.value).format('yyyy-MM-dd HH:mm:ss'),
      method: this.data.method,
      entrust: {
        day: parseInt(parseFloat(this.data.dayp) * 100),
      },
      custom: {
        day: parseInt(parseFloat(this.data.dayp) * 100)
      },
      onsite: {
        flag: this.data.svc_onsite,
        area: this.data.onsite_area,
        addr: this.data.onsite_addr,
        locs: this.data.onsite_locs
      },
      remote: {
        flag: this.data.svc_remote,
        area: this.data.onsite_area,
        addr: this.data.onsite_addr,
        locs: this.data.onsite_locs
      },
      totalStr: this.data.price.totalStr
    }

    App.doPost({
      uri: '/app/order/create/share/tag',
      body: body,
      fnSucc: resp => {
        wx.navigateTo({
          url: '/pages/funcs/share',
          success: (res) => {
            res.eventChannel.emit('accept', {
              type: 'order_share',
              info: {
                car: this.data.car,
                param: body,
                data: resp.data
              }
            })
          }
        })
      },
      fnFail: resp => {
        Util.Notify.error(`[${resp.stat.err}] ${resp.stat.msg}`)
      }
    })
  },

  // 选择地点
  doSelectLocs(e) {
    let lng = this.data.onsite_locs ? parseFloat(this.data.onsite_locs.split(',')[0]) : undefined
    let lat = this.data.onsite_locs ? parseFloat(this.data.onsite_locs.split(',')[1]) : undefined
    wx.chooseLocation({
      longitude: lng,
      latitude: lat,
      success: (res) => {

        let locs = res.longitude.toFixed(6) + ',' + res.latitude.toFixed(6)
        App.doPost({
          uri: '/comm/tool/locs/info',
          body: {
            locs: locs
          },
          fnSucc: resp => {
            if (e.currentTarget.dataset.type == 'onsite') {
              this.setData({
                onsite_addr: res.name,
                onsite_area: resp.data.area.code + "",
                onsite_locs: locs
              })
            } else {
              this.setData({
                onsite_addr: res.name,
                onsite_area: resp.data.area.code + "",
                onsite_locs: locs,
                remote_addr: res.name,
                remote_area: resp.data.area.code + "",
                remote_locs: locs
              })
            }
            this.execCalcPrice()
          },
          fnFail: () => {
            Util.Toast.fail('未知地点信息')
          }
        })
      },
      fail: (err) => {
        console.log(err)
      }
    })
  },
  // 设置日期
  doSetDates(beginTime, closeTime) {
    let begin = {
      value: beginTime.getTime(),
      year: beginTime.format('yyyy'),
      date: beginTime.format('MM月dd日'),
      time: beginTime.format('HH:mm'),
    }
    let close = {
      value: closeTime.getTime(),
      year: closeTime.format('yyyy'),
      date: closeTime.format('MM月dd日'),
      time: closeTime.format('HH:mm'),
    }
    this.setData({
      begin: begin,
      close: close,
      hdays: Kits.getDateMemo(beginTime, closeTime)
    })
    this.execCheckTime()
    this.execCalcPrice()
  },
  doShowFeeDetails() {
    if (this.data.method != 1) {
      return
    }
    this.setData({
      feeDetail: true
    })
  },
  doHideFeeDetails() {
    this.setData({
      feeDetail: false
    })
  },
  doSelectPicker() {
    this.setData({
      pickerSelect: true
    })
  },
  hideSelectPicker() {
    this.setData({
      pickerSelect: false
    })
  },
  doPickerChange(e) {
    this.setData({
      picker: e.currentTarget.dataset.picker,
      pickerSelect: false
    })
  },
  // 跳转选择日期界面
  toSelectDate() {
    wx.navigateTo({
      url: `/pages/order/calendar?carid=${this.data.car.id}&begin=${this.data.begin.value}&close=${this.data.close.value}`,
      events: {
        enter: (e) => {
          this.doSetDates(new Date(e.begin), new Date(e.close))
        }
      }
    })
  },
  // 跳转填写发票信息
  toSelectInvoice() {
    wx.navigateTo({
      url: `/pages/order/invoice`,
      events: {
        enter: (e) => {
          this.setData({
            invoice: e
          })
        }
      },
      success: (res) => {
        res.eventChannel.emit('current', this.data.invoice)
      }
    })
  },
  toAddPicker() {
    wx.navigateTo({
      url: '/pages/mine/picker/index',
    })
  },
  // 转到个人中心
  toUser() {
    wx.navigateTo({
      url: '/pages/mine/info/user',
    })
  },
  // 更换下单方式
  doOrderMethodChange(e) {
    this.setData({
      method: parseInt(e.currentTarget.dataset.type)
    })
    this.execCalcPrice()
  },
  // 更换取车方式
  doOnsiteTypeChange(e) {
    this.setData({
      svc_onsite: (e.currentTarget.dataset.type) == 'true'
    })
    this.execCalcPrice()
  },
  // 更换还车方式
  doRemoteTypeChange(e) {
    this.setData({
      svc_remote: (e.currentTarget.dataset.type) == 'true'
    })
    this.execCalcPrice()
  },
  // 更换押金方式
  doDepoTypeChange(e) {
    if (parseInt(e.currentTarget.dataset.type) == 1 && !this.data.car.service.waive.flag) return
    this.setData({
      depotype: parseInt(e.currentTarget.dataset.type)
    })
  },
  // 检查数字输入
  doCheckInput(e) {
    let value = parseFloat(e.detail.value || '0')
    let min = parseFloat(e.target.dataset.min || '0')
    let max = parseFloat(e.target.dataset.max || '99999')
    if (value < min) {
      return min + ''
    }
    if (value > max) {
      return max + ''
    }
    return parseFloat(value.toFixed(2)) + ''
  },
  doPreviewItem(e) {
    if(!this.data.car.photo) return
    let sources = []
    this.data.car.photo.forEach(p => {
      sources[sources.length] = {
        url: p,
        type: 'image'
      }
    })

    wx.previewMedia({
      sources: sources,
      current: 0
    })
  },
})